<?php

namespace app\api\controller;

use think\Cache;
use think\Db;
use app\common\controller\Api;
use app\common\model\User;
use app\common\model\score\Task as TaskModel;

/**
 * 任务
 */
class Task extends Api
{
    protected $noNeedLogin = '';
    protected $noNeedRight = '*';

    /**
     *  签到任务的标签
     */
    private $user_sign_task_id = 9;

    /**
     *  邀请任务的标签
     */
    private $user_invite_task_id = 4;

     /**
     *  发布赏金广告
     */
    private $user_post_ad_task_id = 10;

     /**
     *  发布印刷需求
     */
    private $user_post_print_task_id = 11;
    /**
     * 任務大廳
     */
    public function home(){
        $user_id = $this->auth->id;

        #签到情况
        $list['post'] = [
            'ad' => TaskModel::cache(300)->field('name, score')->find($this->user_post_ad_task_id),
            'print' => TaskModel::cache(300)->field('name, score')->find($this->user_post_print_task_id),
        ];

        #签到情况
        $list['sign_day'] = $this->maxsignday();

        #签到情况
        $list['sign'] = $this->signList(true);

        #邀请情况
        $list['invite'] = $this->invite(true);

        #任务列表
        $list['new_user'] = collection(TaskModel::where('status',1)->where('type', TaskModel::TASK_TYPE_NEWUSER)->order('id asc')->select())->each(function($item) use($user_id){
            $item->is_done = $item->taskIsDone($item, $user_id);
        });

        $list['dayly'] = collection(TaskModel::where('status',1)->where('type', TaskModel::TASK_TYPE_DAYLY)->order('id asc')->select())->each(function($item) use($user_id){
            $item->is_done = $item->taskIsDone($item, $user_id);
        });


        $this->success('task', $list);

    }

    protected function isSign($date = null){
        $user_id =  $this->auth->id;
        $where['user_id'] = $user_id;
        $where['date'] = $date ? $date :date('Y-m-d');
        return Db::name('self_sign_log')->where($where)->count();
    }

    /*
     * 签到
     */
    public function addSign(){
        //是否已签到
        if($this->isSign()){
            $this->error('今天已签到');
        }
        $user_id =  $this->auth->id;
        //添加签到
        $add_data['user_id'] = $user_id;
        $add_data['createtime'] = time();
        $add_data['date'] = date('Y-m-d');
        $is_success = Db::name('self_sign_log')->insertGetId($add_data);
        //修改积分
        if($is_success){
            //任务记录
            TaskModel::execute_task($this->user_sign_task_id, $user_id);
            if($this->isSign(date('Y-m-d', strtotime("-1 day")))){
                User::where(array('id'=>$user_id))->setInc('maxsigns');
            }else{
                User::where(array('id'=>$user_id))->update(array('maxsigns'=>1));
            }
            $this->success('操作成功');
        }else{
            $this->error('操作失败');
        }
    }
    /*
     * 签到列表
     */
    public function signList($return = 0){

        $weekKey = ["周日","周一","周二","周三","周四","周五","周六"];

        //当前日期
        $sdefaultDate = date("Y-m-d");
        //$first =1 表示每周星期一为开始日期 0表示每周日为开始日期
        $first=1;
        //获取当前周的第几天 周日是 0 周一到周六是 1 - 6
        $w= date('w',strtotime($sdefaultDate));
        //获取本周开始日期，如果$w是0，则表示周日，减去 6 天，此处做处理加一天，按中国人的习惯
        $week_start = date('Y-m-d',strtotime("$sdefaultDate -".($w ? $w - $first : 6).' days'));

        //本周结束日期
        $week_end = date('Y-m-d',strtotime("$week_start +6 days"));


        //签到任务
        $score = TaskModel::where('id',$this->user_sign_task_id)->value('score');

        $start = strtotime($week_start);
        $end = strtotime($week_end." 23:59:59");
        $where['createtime'] = array('between', array($start, $end));
        $where['user_id'] = $this->auth->id;

        $weekly_data = Db::name('self_sign_log')->field("date")->where($where)->select();

        $wdays = [];
        foreach($weekly_data as $k => $l){
            $wdays[$l['date']] = 1;
        }

        $today = date("Y-m-d");

        $week_array = [];

        for($time = $start; $time < $end; $time += 86400){
            $date = date("Y-m-d", $time);
            $index = date('w', $time);
            $week_array[] = [
                'date'  => $date,
                'score' => $score ? $score : 0,
                'index'  => $index,
                'today'  => $today == $date,
                'name'  => $weekKey[$index],
                'is_sign' => isset($wdays[$date]) ? 1 : 0
            ];
        }

        if($return) return $week_array;

        $this->success('签到记录', $week_array);
    } 

    /*
     * 邀请情况
     */
    public function invite($return = 0){
        $invi_task = TaskModel::cache(300)->field('name, score')->find($this->user_invite_task_id);
        //今日邀请
        $today_start = strtotime(date('Y-m-d'));
        $today_end = strtotime(date('Y-m-d').'+1 day');
        $where['top_id'] = $this->auth->id;
        $where['jointime'] = array('between', array($today_start, $today_end));

        $today_invi = User::where($where)->field('id,nickname,avatar')->order('id desc')->paginate(4)->toArray();


        $a = $today_invi['data'];

        $today_invi['data'] = array_pad($a, 4, [
            'id' => 0,
            'nickname' => '',
            'avatar' => '',
        ]);

        foreach($today_invi['data'] as $key => &$val){
            $val['score'] = $invi_task['score'];
        }

        if($return){
            return [
                'task' => $invi_task,
                'list' => $today_invi,
            ];
        }

        $this->success('邀请情况', [
            'task' => $invi_task,
            'list' => $today_invi,
        ]);

    }

    private function maxsignday (){

        if(!$this->isSign() && !$this->isSign(date('Y-m-d', strtotime("-1 day")))){
            return 0;
        }

        return User::where('id', $this->auth->id)->value('maxsigns');
    }
}